package com.controller;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.po.EquityRecord;
import com.po.Image;
import com.po.Staff;
import com.service.EquityRecordService;
import com.service.ImageService;
import com.service.StaffService;


@Controller("/equityrecord")
@RequestMapping(value = "/equityrecord")
public class EquityRecordController {
	@Autowired
	private StaffService staffService;
	@Autowired
	private EquityRecordService equityRecordService;
	@Autowired
	private ImageService imageService;
	
	@RequestMapping(value = "/list",method = RequestMethod.GET)
	public String list(Model model,EquityRecord record){
		
		
		
		if(record.getStaffName() ==null && record.getCreateTimesearch() ==null&& record.getStopTimesearch()==null)
		{
		List<EquityRecord> paging = equityRecordService.list();
		model.addAttribute("list", paging);
		}else
		{
			//try {
				if (record != null){
				//	String a = new String(record.getStaffNamesearch().getBytes("ISO8859_1"),"UTF-8");
				
					//record.setStaffNamesearch(a);
					
					List<EquityRecord> paging =equityRecordService.searchlist(record);
					model.addAttribute("list", paging);
				}
		//	} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
			//	e.printStackTrace();
			//}
			
			
		}
	    return  "equityrecord/list";
	}

	@RequestMapping(value = "/edit")
	public Object save(Integer id,Model model){
		Staff staff = staffService.findById(id);
	    model.addAttribute("staff", staff);
	    return "equityrecord/detail";
	}
	
	@RequestMapping(value = "/del")
	public Object del(@RequestParam(value="id") Integer id){
		equityRecordService.del(id);
	    return "redirect:/equityrecord/list.htm ";
	}
	
	
	@RequestMapping(value = "/index")
	public String IntegralReport(Model model){
		List<EquityRecord> paging = equityRecordService.IntegralReport();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月");    
        c.setTime(new Date());//设置当前日期  
        c.add(Calendar.MONTH, -1);//月份减一  
        String date2 = sdf.format(c.getTime());
        c.add(Calendar.MONTH, -1);
        String date1 = sdf.format(c.getTime());
	    model.addAttribute("thisym", date2);
		
		model.addAttribute("lastym", date1);
		  //每页展示8条，则总list %8 取余数 
		  int i	= paging.size()%8; //余数
		  int i1	= paging.size()/8;  //取商
		 
		  if(i>0){ //余数大于0时 页数加一页
			    int i3= (i1+1);
			    List te =  EquityRecordController.splitList(paging,i3);
			    model.addAttribute("integralreport", te);//返回页面
			    List te1= EquityRecordController.splitList(te,2);
				  model.addAttribute("integralreport1", te1.get(0));
				  model.addAttribute("integralreport2", te1.get(1));
			  }
			    else{
		  
		  List te =  EquityRecordController.splitList(paging,i1); //页数生产对应list 
		  model.addAttribute("integralreport", te);
		  
        
		
		//  model.addAttribute("integralreport2", te1.get(1));
		  }
		    return  "equityrecord/index";
		}

	
	@RequestMapping(value = "/report")
	public String report(Model model){
		List<Image> img = imageService.List();
		model.addAttribute("imglist", img);
		List<EquityRecord> paging = equityRecordService.IntegralReport();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月");    
        c.setTime(new Date());//设置当前日期  
        c.add(Calendar.MONTH, -1);//月份减一  
        String date2 = sdf.format(c.getTime());
        c.add(Calendar.MONTH, -1);
        String date1 = sdf.format(c.getTime());
	    model.addAttribute("thisym", date2);
		model.addAttribute("lastym", date1);
		

		StringBuilder html = new StringBuilder(1024);
		String head = "<div class=\"lzy-%s\"><table class=\"lzy-table\"><thead><tr><th>部门</th><th>姓名</th><th>"+date1+"</th><th>"+date2+"</th><th>总积分</th></tr></thead><tbody>";
		String foot = "</tbody></table></div><div class=\"btm-info\"><h2>获得股权激励方式：</h2><div class=\"btm-left\"><p>1、创业时间（18点后，50股/小时）</p><p>2、特殊贡献（10000股/次——100000股/次）</p></div></div>";
		String dir = "l";
		
		html.append("<div class=\"swiper-slide\">");
		html.append(String.format(head, dir));
		for(int i = 0;i < paging.size() ; i++){
			EquityRecord item = paging.get(i);
			html.append(String.format("<tr><td>%s</td><td>%s</td><td>%d</td><td>%d</td><td>%d</td></tr>", 
					item.getdepartment(),item.getStaffName(),item.getLastMonth(),item.getThisMonth(),item.getEquityval()));
			
			if ((i + 1) % 4 == 0) {
				html.append(foot);
				if ((i+1) % 8 == 0) {
					html.append("</div><div class=\"swiper-slide\">");
				}
				html.append(String.format(head, dir == "l" ? "r" : "l"));
				dir = (dir == "l" ? "r" : "l");
			}
		}
		
		
		int num = paging.size() % 4;
		if(num > 0) {
			for(int i = 1 ; i <= num ; i++) {
				html.append("<tr><td>　</td><td>　</td><td>　</td><td>　</td><td>　</td></tr>");
			}
		}
		
		
		html.append(foot);
		
		html.append("</div>");
		
		
		model.addAttribute("body", html.toString());
		
		
		return "equityrecord/report";
	}
	
	
	public static <T> List<List<T>> splitList(List<T> source,int n){  
	    List<List<T>> result=new ArrayList<List<T>>();  
	    int remaider=source.size()%n;  //(先计算出余数)  
	    int number=source.size()/n;  //然后是商  
	    int offset=0;//偏移量  
	    for(int i=0;i<n;i++){  
	        List<T> value=null;  
	        if(remaider>0){  
	        	 	 value=source.subList(i*number+offset, (i+1)*number+offset+1);  
	        		 remaider--;  
		 	            offset++;
	        	 
	             
	        }else{  
	        	
	        	 value=source.subList(i*number+offset, (i+1)*number+offset);  
	        }  
	        result.add(value);  
	    }  
	    return result;  
	}
	//股权变更页面
	@RequestMapping(value = "/update")
	public Object update(Integer id,Model model){
		EquityRecord equityRecord  = equityRecordService.findById(id);
		model.addAttribute("equityRecord", equityRecord);
		return "equityrecord/update";
	}
	/**
	 * 变更股权页面保存
	 * @param er
	 * @return
	 */
	@RequestMapping(value = "/saveEquity")
	public String saveEquity(@ModelAttribute EquityRecord er){

		EquityRecord equityRecord  = equityRecordService.findById(er.getId());
		int sum =er.getNum() -equityRecord.getNum();
		equityRecordService.update(er);
		//修改主表
		Staff staff = staffService.findById(er.getStaffid());
		staff.setEquityval(staff.getEquityval()+sum);
		staffService.update(staff);
		return "redirect:/equityrecord/list.htm ";
	}

}
